package com.dl.study.controller;

import com.dl.study.domain.WorkFlow;
import com.dl.study.domain.WorkFlowStep;
import com.dl.study.service.FlowService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.bpmn.model.*;
import org.activiti.bpmn.BpmnAutoLayout;
import org.activiti.bpmn.model.Process;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RepositoryService;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: denglei
 * @Date: 2021/12/8 14:23
 * @Description:
 */
@RestController
public class FlowController {
    @Autowired
    private FlowService flowService;


    //测试0001

    @PostMapping("/deploy")
    public Object createDeploy(){
       return flowService.createDeploy();
    }

    @Autowired
    private RepositoryService repositoryService;  //流程定义和流程部署相关功能

    @Autowired
    private ProcessEngine processEngine;  //流程引擎

    /**
     * 动态流程实例并输出png和xml
     *
     * @throws IOException
     */
    @GetMapping("/createDeployment3")
    public String createDeployment3() throws IOException {
        //模拟前端页面数据
        WorkFlow workFlow = new WorkFlow(1, "test", "流程测试");
        List<WorkFlowStep> stepList = new ArrayList<>();
        List<Integer> childList1 = new ArrayList<>();
        childList1.add(2);
        WorkFlowStep s1 = new WorkFlowStep(1, workFlow.getId(), "start", 1, 1, childList1, null, null);
        List<Integer> childList2 = new ArrayList<>();
        childList2.add(3);
        childList2.add(4);
        WorkFlowStep s2 = new WorkFlowStep(2, workFlow.getId(), "parallelGateway-fork", 2, 2, childList2, null, "a");
        List<Integer> childList3 = new ArrayList<>();
        childList3.add(6);
        WorkFlowStep s3 = new WorkFlowStep(3, workFlow.getId(), "task1", 0, 3, childList3, null, "a");
        List<Integer> childList4 = new ArrayList<>();
        childList4.add(5);
        WorkFlowStep s4 = new WorkFlowStep(4, workFlow.getId(), "task2", 0, 4, childList4, null, "a");
        List<Integer> childList5 = new ArrayList<>();
        childList5.add(6);
        WorkFlowStep s5 = new WorkFlowStep(5, workFlow.getId(), "task22", 0, 5, childList5, null, "a");
        List<Integer> childList6 = new ArrayList<>();
        childList6.add(7);
        WorkFlowStep s6 = new WorkFlowStep(6, workFlow.getId(), "parallelGateway-join", 3, 6, childList6, null, "a");
        List<Integer> childList7 = new ArrayList<>();
        childList7.add(8);
        childList7.add(9);
        WorkFlowStep s7 = new WorkFlowStep(7, workFlow.getId(), "exclusiveGate", 4, 7, childList7, null, "a");
        List<Integer> childList8 = new ArrayList<>();
        childList8.add(10);
        WorkFlowStep s8 = new WorkFlowStep(8, workFlow.getId(), "task3", 0, 8, childList8, "${flag=='true'}", "a");
        List<Integer> childList9 = new ArrayList<>();
        childList9.add(10);
        WorkFlowStep s9 = new WorkFlowStep(9, workFlow.getId(), "task4", 0, 9, childList9, "${flag=='false'}", "a");
        List<Integer> childList10 = new ArrayList<>();
        childList10.add(11);
        WorkFlowStep s10 = new WorkFlowStep(10, workFlow.getId(), "receiveTask", 6, 10, childList10, null, "a");
        WorkFlowStep s11 = new WorkFlowStep(11, workFlow.getId(), "end", 5, 11, new ArrayList<>(), null, "a");

        stepList.add(s1);
        stepList.add(s2);
        stepList.add(s3);
        stepList.add(s4);
        stepList.add(s5);
        stepList.add(s6);
        stepList.add(s7);
        stepList.add(s8);
        stepList.add(s9);
        stepList.add(s10);
        stepList.add(s11);


        //创建ProcessEngine对象
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        //得到RepositoryService
        RepositoryService repositoryService = processEngine.getRepositoryService();

        // 1. 建立模型
        BpmnModel model = new BpmnModel();
        Process process = new Process();
        model.addProcess(process);
        process.setId(workFlow.getName());
        process.setName(workFlow.getName());
        stepList.forEach(step -> {
            if (step.getType() == 1) {
                process.addFlowElement(createStartEvent());
            } else if (step.getType() == 5) {
                process.addFlowElement(createEndEvent());
            } else if (step.getType() == 2 || step.getType() == 3) {
                process.addFlowElement(createParallelGateway(step.getName(), step.getName()));

            } else if (step.getType() == 4) {
                process.addFlowElement(createExclusiveGateway(step.getName(), step.getName()));
            } else if (step.getType() == 6) {
                process.addFlowElement(createReceiveTask(step.getName(), step.getName()));
            } else {
                process.addFlowElement(createUserTask(step.getName(), step.getName(), step.getAssignee()));
            }
        });

        //连线
        stepList.forEach(step -> {
            List<Integer> childList = step.getChlidOrderIds();
            childList.forEach(child -> {
                stepList.forEach(step1 -> {
                    if (step1.getOrderId() == child) {
                        if (step.getType() == 4) {
                            process.addFlowElement(createSequenceFlow(step.getName(), step1.getName(), step1.getConditionExpression()));
                        } else {
                            process.addFlowElement(createSequenceFlow(step.getName(), step1.getName(), null));
                        }
                    }
                });
            });
        });


        //定义并设置流程变量
        Map<String, Object> variables = new HashMap<>();
        variables.put("flag", 1 == 2);
        //deploy
        Deployment deployment = repositoryService.createDeployment().addBpmnModel("process/dynamic-model.bpmn", model).name("Dynamic process deployment").deploy();

        System.out.println("deploymentId:"+deployment.getId());
        //start
        ProcessInstance processInstance = processEngine.getRuntimeService().startProcessInstanceByKey(workFlow.getName(), variables);
        System.out.println("processInstanceId:" + processInstance.getId());
        System.out.println("getProcessDefinitionId:"+processInstance.getProcessDefinitionId());

        BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());
        //save as  png
        new BpmnAutoLayout(bpmnModel).execute();
        List<String> highLightedActivities = processEngine.getRuntimeService().getActiveActivityIds(processInstance.getId());// 高亮节点
        List<String> highLightedFlows = new ArrayList<>(); // 高亮连接线
        ProcessDiagramGenerator processDiagramGenerator = new DefaultProcessDiagramGenerator();
        InputStream inputStream = processDiagramGenerator.generateDiagram(bpmnModel, "png", highLightedActivities, highLightedFlows, "宋体", "宋体", "宋体", null, 1.0);
        FileUtils.copyInputStreamToFile(inputStream, new File("C:\\Users\\Administrator\\Desktop\\process.png"));
        //save sa  xml
        InputStream inputStreamXml = processEngine.getRepositoryService().getResourceAsStream(deployment.getId(), "process/dynamic-model.bpmn");
        FileUtils.copyInputStreamToFile(inputStreamXml, new File("C:\\Users\\Administrator\\Desktop\\process.bpmn.xml"));
        return processInstance.getId();
    }

    /**
     * 开始事件
     *
     * @return
     */
    StartEvent createStartEvent() {
        StartEvent startEvent = new StartEvent();
        startEvent.setId("start");
        return startEvent;
    }

    /**
     * 结束事件
     *
     * @return
     */
    EndEvent createEndEvent() {
        EndEvent endEvent = new EndEvent();
        endEvent.setId("end");
        return endEvent;
    }

    /**
     * 创建用户任务
     *
     * @param id
     * @param name
     * @param assignee
     * @return
     */
    UserTask createUserTask(String id, String name, String assignee) {
        UserTask userTask = new UserTask();
        userTask.setName(name);
        userTask.setId(id);
        userTask.setAssignee(assignee);
        return userTask;
    }

    /**
     * 创建接收任务
     *
     * @param id
     * @param name
     * @return
     */
    ReceiveTask createReceiveTask(String id, String name) {
        ReceiveTask receiveTask = new ReceiveTask();
        receiveTask.setId(id);
        receiveTask.setName(name);
        return receiveTask;
    }


    /**
     * 连线
     *
     * @param from
     * @param to
     * @return
     */
    SequenceFlow createSequenceFlow(String from, String to, String conditionExpression) {
        SequenceFlow sequenceFlow = new SequenceFlow();
        sequenceFlow.setSourceRef(from);
        sequenceFlow.setTargetRef(to);
        if (StringUtils.isNotBlank(conditionExpression)) {
            sequenceFlow.setConditionExpression(conditionExpression);
        }
        return sequenceFlow;
    }

    /**
     * 排他网关
     *
     * @param id
     * @param name
     * @return
     */
    ExclusiveGateway createExclusiveGateway(String id, String name) {
        ExclusiveGateway exclusiveGateway = new ExclusiveGateway();
        exclusiveGateway.setId(id);
        exclusiveGateway.setName(name);
        return exclusiveGateway;
    }

    /**
     * 并行网关
     *
     * @return
     */
    ParallelGateway createParallelGateway(String id, String name) {
        ParallelGateway parallelGateway = new ParallelGateway();
        parallelGateway.setId(id);
        parallelGateway.setName(name);
        return parallelGateway;

    }

}
